package org.niit.stream

import org.apache.spark.SparkConf
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Seconds, StreamingContext}

object SparkStreaming_07 {

  /*
   window 窗口采集
   */
  def main(args: Array[String]): Unit = {

    val sparkConf: SparkConf = new SparkConf().setMaster("local[*]").setAppName("spark")
    val ssc = new StreamingContext(sparkConf, Seconds(3))
    ssc.sparkContext.setLogLevel("ERROR")


    val lines: ReceiverInputDStream[String] = ssc.socketTextStream("localhost", 9999)

    val flatMap: DStream[String] = lines.flatMap(_.split(" "))
    val map: DStream[(String, Int)] = flatMap.map((_, 1))

    /*
       窗口的范围必须是采集周期的整数倍
       第一个参数：窗口时长 （一次采集几个采集周期的数据）
       第二个参数：滑块步长 （窗口移动几个周期）
     */
    val winDS: DStream[(String, Int)] = map.window(Seconds(6), Seconds(6))

    val resDS: DStream[(String, Int)] = winDS.reduceByKey(_ + _)

    resDS.print()

    ssc.start()
    ssc.awaitTermination()

  }

}
